import {take, call, put, fork, cancel} from 'redux-saga/effects';
import AuthManager from '../services/auth'
import * as Actions from '../actions/index'
import * as Types from '../actions/ActionTypes.js'
import * as api from '../services/notification';
import {message, notification, Button} from 'antd';
import callServiceApi from './utils';
import React from 'react';
import { hashHistory } from 'react-router'

function* watchNotificationUnreadQuery() {
  while (true) {
    yield take(Types.NOTIFICATION_UNREAD_QUERY.REQUEST);
    yield fork(notificationUnreadQuery);
  }
}

function* watchNotificationMarkReaded() {
  while (true) {
    const { payload } = yield take(Types.NOTIFICATION_MARK_READED.REQUEST);
    yield fork(notificationMarkReaded, payload);
    const action = yield take([Types.NOTIFICATION_MARK_READED.SUCCESS, Types.NOTIFICATION_MARK_READED.FAILURE])
    if(action.type == Types.NOTIFICATION_MARK_READED.SUCCESS) {
      yield put(Actions.notificationUnreadQuery.request()());
    }
  }
}

function* watchNotificationNewQuery() {
  while (true) {
    yield take(Types.NOTIFICATION_NEW_QUERY.REQUEST);
    yield fork(notificationNewQuery);
    const action = yield take([Types.NOTIFICATION_NEW_QUERY.SUCCESS, Types.NOTIFICATION_NEW_QUERY.FAILURE])
    if(action.type == Types.NOTIFICATION_NEW_QUERY.SUCCESS) {
      action.payload.forEach((item) => {
        const openNotification = function () {
          const key = `open${Date.now()}`;
          const btnClick = function () {
            // to hide notification box
            notification.close(key);
            hashHistory.push({ pathname: `${item.action}`, state: { studentId: item.param, mode:'Edit', back:'/order/check' }});
          };
          const btn = (
            <Button type="primary" size="small" onClick={btnClick}>
              查看
            </Button>
          );
          notification.open({
            message: '系统通知',
            description: `${item.descTime}, ${item.title}`,
            btn,
            key,
            onClose: close,
            duration: 0,
          });
        };

        openNotification();
      });
    }
  }
}
function* notificationUnreadQuery() {
  yield fork(callServiceApi, Actions.notificationUnreadQuery, api.notificationoUnreadQuery, {});
}

function* notificationNewQuery() {
  yield fork(callServiceApi, Actions.notificationNewQuery, api.notificationNewQuery, {});
}

function* notificationMarkReaded(ids) {
  yield fork(callServiceApi, Actions.notificationMarkReaded, api.notificationMarkReaded, ids);
}

export default function*() {
  yield [
    fork(watchNotificationUnreadQuery),
    fork(watchNotificationNewQuery),
    fork(watchNotificationMarkReaded),
  ];
}
